﻿using UnityEngine;
using System.Collections;
using UnityEditor;

public class UGUIMenuItem
{

    [MenuItem("UGUI/ClipRatioRect #r")]
    public static void ClipRatioRect()
    {
        if (Selection.activeGameObject != null)
        {
            RectTransform rectTrans = Selection.activeGameObject.GetComponent<RectTransform>();
            if(rectTrans != null)
            {
                if(rectTrans.pivot != Vector2.up)
                {
                    Debug.LogError("Set RectTransform to origin");
                    return;
                }
                else
                {

                    // Calculate by anchors
                    AnchorsToCorners();

                    // Calculate ratio in current screen size
                    float x = rectTrans.anchorMin.x;
                    float y = 1f - rectTrans.anchorMax.y; // Caution: origin y is opposite
                    float w = rectTrans.anchorMax.x - rectTrans.anchorMin.x;
                    float h = rectTrans.anchorMax.y - rectTrans.anchorMin.y;

                    // Copy to the clipboard
                    string s = string.Format("GUIHelper.RatioRect({0}f, {1}f, {2}f, {3}f)", x, y, w, h);
                    System.Diagnostics.Process.Start("CMD.exe", string.Format("/C  echo {0} | clip", s));

                    Debug.Log("Copied " + s + " to the clipboard");
                }
            }
        }
    }

    #region  Supported by Senshi

    [MenuItem("UGUI/Anchors to Corners %[")]
    public static void AnchorsToCorners()
    {
        RectTransform t = Selection.activeTransform as RectTransform;
        RectTransform pt = Selection.activeTransform.parent as RectTransform;

        if (t == null || pt == null) return;

        Vector2 newAnchorsMin = new Vector2(t.anchorMin.x + t.offsetMin.x / pt.rect.width,
                                            t.anchorMin.y + t.offsetMin.y / pt.rect.height);
        Vector2 newAnchorsMax = new Vector2(t.anchorMax.x + t.offsetMax.x / pt.rect.width,
                                            t.anchorMax.y + t.offsetMax.y / pt.rect.height);

        t.anchorMin = newAnchorsMin;
        t.anchorMax = newAnchorsMax;
        t.offsetMin = t.offsetMax = new Vector2(0, 0);
    }

    [MenuItem("UGUI/Corners to Anchors %]")]
    public static void CornersToAnchors()
    {
        RectTransform t = Selection.activeTransform as RectTransform;

        if (t == null) return;

        t.offsetMin = t.offsetMax = new Vector2(0, 0);
    }

    #endregion


}
